package org.example.demo;

import java.sql.*;
import java.text.MessageFormat;

public class demo1_DriverManager {
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        //1.加载数据库厂商提供的驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.简历数据库连接
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mysql123?characterEncoding=utf8" +
                    "&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&useSSL=false", "root", "123456");
            //3.创建Statement对象
            statement = connection.createStatement();
            //4.定义sql语句
            String sql = "select id,name from users";
            //5.执行sql
            resultSet = statement.executeQuery(sql);
            //6.遍历结果集，获取数据行,resultSet.next()返回一个boolean值，true表示有下一条记录
            while (resultSet.next()) {
                //每进入一次循环表示读取一行新记录
                //获取id列的值，根据列的数据类型不同调用不同的方法
                long id = resultSet.getLong(1);
                //依次获取其他列的值
                String name = resultSet.getString(2);
                System.out.println(MessageFormat.format("编号={0},姓名={1}",id,name));
            }
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        } finally {
            //依次释放资源
            if (resultSet != null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
























